import {
  defineStore
} from 'pinia'
import {
  ref
} from 'vue';
import {
  chainSendAndRequest
} from '@/utils/SocketDUtil.js'

export const useMetadataStore = defineStore('metadata', () => {
  const mdlist = ref([])
  const packagePath = ref('')
  const mdTableSelectedKeys = ref([])

  function clear() {
    mdlist.value = []
    packagePath.value = ''
    mdTableSelectedKeys.value = []
  }

  function getMdlist() {

    return chainSendAndRequest('/metadata/MDList').then((resp) => {
      let list = resp
      if (!list && list.lenght < 1)
        return;

      mdlist.value = list
      mdlist.value.forEach(md => {
        let defaultSelectedColunmKeys = md.columns.map(col => col.columnName)
        Object.assign(md, {
          colunmSelectedKeys: ref(defaultSelectedColunmKeys)
        })
      })
    })


  }

  function selectedMDlist() {
    let mds = mdlist.value.filter(md => mdTableSelectedKeys.value.includes(md.tableName))
    mds.forEach(md => md.columns = md.columns.filter(col => md.colunmSelectedKeys.includes(col.columnName)))
    return mds
  }

  return {
    mdlist,
    packagePath,
    mdTableSelectedKeys,
    getMdlist,
    selectedMDlist,
    clear
  }
})